package com.yuanheng100.ems4j.service;

import com.alibaba.fastjson.JSON;
import com.yuanheng100.ems4j.api.IMenuService;
import com.yuanheng100.ems4j.mapper.Ems4jMenuMapper;
import com.yuanheng100.ems4j.mapper.Ems4jRoleMapper;
import com.yuanheng100.ems4j.model.Ems4jMenu;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Created by jlqian on 2017/1/11.
 */
@Service
public class MenuServiceImpl implements IMenuService
{
    private static Logger logger = LoggerFactory.getLogger(MenuServiceImpl.class);

    @Autowired
    private Ems4jMenuMapper ems4jMenuMapper;
    @Autowired
    private Ems4jRoleMapper ems4jRoleMapper;

    @Override
    public List<Ems4jMenu> getMenuListByRole(int appId, int roleId)
    {
        return ems4jMenuMapper.selectMenuListByAppIdAndRoleId(appId, roleId);
    }

    @Override
    public int addMenu(Ems4jMenu menu)
    {
        logger.info("新增菜单：" + JSON.toJSONString(menu));
        return ems4jMenuMapper.insert(menu);
    }

    @Override
    public int updateMenu(Ems4jMenu menu)
    {
        logger.info("修改菜单：" + JSON.toJSONString(menu));
        return ems4jMenuMapper.updateByPrimaryKey(menu);
    }

    @Override
    public int addMenuToRole(int menuId, int roleId)
    {
        //校验Menu和Role是否都存在
        if (ems4jMenuMapper.selectByPrimaryKey(menuId) != null && ems4jRoleMapper.selectByPrimaryKey(roleId) != null)
        {
            logger.info("对角色" + roleId + "增加菜单" + menuId);
            return ems4jMenuMapper.addMenuToRole(menuId, roleId);
        }
        return 0;
    }

    @Override
    public int removeMenuFromRole(int menuId, int roleId)
    {
        logger.info("从角色" + roleId + "移除菜单" + menuId);
        return ems4jMenuMapper.removeMenuFromRole(menuId, roleId);
    }

    @Override
    public int deleteMenu(int menuId)
    {
        logger.info("删除菜单：" + menuId);
        //删除 角色-菜单 关联
        ems4jMenuMapper.deleteRoleMenuByMenuId(menuId);
        //删除菜单
        return ems4jMenuMapper.deleteByPrimaryKey(menuId);
    }
}
